//
//  GoodDetailViewController.m
//  WisdomZhuHai
//
//  Created by Ryan on 14-12-16.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "GoodDetailViewController.h"
#import "OrderViewController.h"
#import "EmptyViewController.h"
#import "TransforController.h"
#import "BottomBarViewController.h"
#import "MobClick.h"

static const CGFloat IMAGECELL_HEIGHT = 180;
static const CGFloat PRICE_HEIGHT = 40;
static const CGFloat TICKET_HEIGHT = 203;
static const CGFloat CINEMA_HEIGHT = 180;

@interface GoodDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong)NSDictionary* goodDetail;
@property (nonatomic,assign)CGFloat useLimitList;


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) BottomBarViewController *bottomBarController;

@end

@implementation GoodDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.view setFrame:[UIScreen mainScreen].bounds];
    
    UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0];
    [self.view addSubview:view_navigationBar];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + HEIGHT_STATUS_BAR + HEIGHT_NAVIGATION_BAR, self.view.frame.size.width, self.view.frame.size.height - HEIGHT_BOTTOM_BAR - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
//    [self.tableView setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height - HEIGHT_BOTTOM_BAR)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.title = @"商品详情";
    [self initToolbar];
    [self getGoodDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initToolbar{
    self.bottomBarController = [[BottomBarViewController alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height - HEIGHT_BOTTOM_BAR, 320, 45)];
    NSLog(@"%s || height of tableview:%f and screen:%f and bottomBar's position: %f, %f", __FUNCTION__, self.tableView.bounds.size.height, [UIScreen mainScreen].bounds.size.height, self.bottomBarController.view.frame.origin.x, self.bottomBarController.view.frame.origin.y);
    if(self.instance_navigation_temp == nil){
        self.bottomBarController.bottomBarNavigationController = self.navigationController;
    }else{
        self.bottomBarController.bottomBarNavigationController = self.instance_navigation_temp;
    }
    
    [self.view addSubview:self.bottomBarController.view];
}


#pragma mark - Protocol
- (void)getGoodDetail
{
    [[ProtocolManager shareInstance] getSingleGoodDetail:self.goodId sendType:@"详情" target:self selector:@selector(getGoodDetailCallback:)];
}

#pragma mark - Callback
- (void)getGoodDetailCallback:(NSDictionary*)dic
{
    NSLog(@"getGoodDetailCallback %@",dic);
    if (dic == nil) {
        return;
    }
    self.goodDetail = dic;
    [self.tableView reloadData];
    if([[Common valueForKey:@"id" dic:dic] length] > 0){
        [self.bottomBarController setEnabledWithData:[NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"GOODS",[Common valueForKey:@"id" dic:dic], nil] forKeys:[NSArray arrayWithObjects:@"type",@"id", nil]]];
    }
}

#pragma mark - Cell
- (void)loadCellData:(UITableViewCell*)cell
{
    if (self.goodDetail.count <= 0) {
        return;
    }
    cell.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    NSDictionary *cellData = self.goodDetail;
    UIImageView *goodImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, IMAGECELL_HEIGHT)];
    NSString *imgUrl = [Common valueForKey:P_PHOTO dic:cellData];
    [goodImage setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
    [cell.contentView addSubview:goodImage];
}

- (void)loadPriceAndNameCellData:(UITableViewCell*)cell index:(int)index
{
    if (self.goodDetail.count <= 0) {
        return;
    }
    cell.backgroundColor = [Common colorWithRGB:0xf5f5f5];
        NSDictionary *cellData = self.goodDetail;
    if (index == 0) {
        NSString *price = [Common valueForKey:P_PREFERENTIAL_PRICE dic:cellData];
        NSString *prePrice = [Common valueForKey:P_PRICE dic:cellData];
        UILabel *prePriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 75, PRICE_HEIGHT)];
        prePriceLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:25.0];
        prePriceLabel.textColor = [UIColor orangeColor];
        if ([prePrice isEqualToString:price] || prePrice == nil || [prePrice isEqualToString:@"0.00"]) {
            prePriceLabel.text = [NSString stringWithFormat:@"%@",price];
        } else {
            prePriceLabel.text = [NSString stringWithFormat:@"%@",prePrice];
        }
        [prePriceLabel sizeToFit];
        CGRect preframe = prePriceLabel.frame;
        preframe.size.height = PRICE_HEIGHT;
        prePriceLabel.frame = preframe;
        UILabel *yuan = [[UILabel alloc] initWithFrame:CGRectMake(prePriceLabel.frame.size.width+13, 8, 60, PRICE_HEIGHT-10)];
        yuan.font = [UIFont fontWithName:@"TrebuchetMS" size:15.0];
        yuan.textColor = [UIColor orangeColor];
        yuan.text = @"元";
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(prePriceLabel.frame.size.width+30, 8, 60, PRICE_HEIGHT-10)];
        priceLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:15.0];
        priceLabel.textColor = [Common colorWithRGB:0xb2b2b2];
        if (![prePrice isEqualToString:price] && (prePrice != nil) && ![prePrice isEqualToString:@"0.00"]) {
            priceLabel.text = [NSString stringWithFormat:@"%@元",price];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 15, priceLabel.frame.size.width, 1)];
            line.backgroundColor = [Common colorWithRGB:0xb2b2b2];
            [priceLabel addSubview:line];
        }
        [cell.contentView addSubview:prePriceLabel];
        [cell.contentView addSubview:yuan];
        [cell.contentView addSubview:priceLabel];
        
        NSString *is_sell = [Common valueForKey:P_IS_SELL dic:cellData];
        NSString *payment_mode = [Common valueForKey:P_PAYMENT dic:cellData];
        if ([is_sell isEqualToString:@"1"]) {
            UIView *btn = [[UIView alloc] initWithFrame:CGRectMake(230, 5, 75, PRICE_HEIGHT-10)];
            btn.layer.cornerRadius = 2.0;
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toBuyTicket:)];
            UILabel *btnLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 60, btn.frame.size.height)];
            btnLabel.textColor = [UIColor whiteColor];
            btnLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:13.0];
            if ([payment_mode isEqualToString:@"0"]) {
                btn.backgroundColor = [Common colorWithRGB:0xf8b62d];
                btnLabel.text = @"立即抢购";
            } else if ([payment_mode isEqualToString:@"1"]) {
                btn.backgroundColor = [Common colorWithRGB:0x47a9f3];
                btnLabel.text = @"立即预约";
            }
            [btn addGestureRecognizer:tapGesture];
            [btn addSubview:btnLabel];
            [cell.contentView addSubview:btn];
        }
    } else {
        NSString *okcash = [NSString stringWithFormat:@"%@", [Common valueForKey:P_V2_OKCASH dic:cellData]];
        NSString *storecash = [NSString stringWithFormat:@"%@", [Common valueForKey:P_V2_STORECASH dic:cellData]];
        NSString *cinemaName = nil;
        if (![okcash isEqualToString:@"0"] && ![storecash isEqualToString:@"0"]) {
            cinemaName = [NSString stringWithFormat:@"购买此商品后可得到%@元商家代金券、%@元OK代金券", storecash, okcash];
        } else if ([okcash isEqualToString:@"0"] && [storecash isEqualToString:@"0"]) {
            cinemaName = @"";
        } else if ([okcash isEqualToString:@"0"]) {
            cinemaName = [NSString stringWithFormat:@"购买此商品后可得到%@元商家代金券", storecash];
        } else if ([storecash isEqualToString:@"0"]) {
            cinemaName = [NSString stringWithFormat:@"购买此商品后可得到%@元OK代金券", okcash];
        }
        UILabel *cinemaLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 320, PRICE_HEIGHT)];
        cinemaLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:12.0];
        cinemaLabel.textColor = [Common colorWithRGB:0xb2b2b2];
        cinemaLabel.text = cinemaName;
        [cell.contentView addSubview:cinemaLabel];
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, PRICE_HEIGHT-1, 290, 1)];
    lineView.backgroundColor = [Common colorWithRGB:0xeaeaea];
    [cell.contentView addSubview:lineView];
}

- (void)loadTicketCell:(UITableViewCell*)cell
{
    if (self.goodDetail.count <= 0) {
        return;
    }
    NSDictionary *cellData = self.goodDetail;
    cell.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    UILabel *nameLabel = (UILabel*)[cell viewWithTag:1001];
    UILabel *priceLabel = (UILabel*)[cell viewWithTag:1003];
    UIView *moreView = [cell viewWithTag:1004];
    nameLabel.text = [Common valueForKey:P_NAME dic:cellData];
    NSString *price = [Common valueForKey:P_PREFERENTIAL_PRICE dic:cellData];
    NSString *prePrice = [Common valueForKey:P_PRICE dic:cellData];
    if (prePrice == nil || [prePrice isEqualToString:@"0.00"]) {
        priceLabel.text = [NSString stringWithFormat:@"%@元",price];
    } else {
        priceLabel.text = [NSString stringWithFormat:@"%@元",prePrice];
    }
    UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toMoreView:)];
    [moreView addGestureRecognizer:tapMore];
}

- (void)loadUseLimitCellData:(UITableViewCell*)cell
{
    if (self.goodDetail.count <= 0) {
        return;
    }
    NSDictionary *cellData = self.goodDetail;
    cell.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    NSString *useLimit = [Common valueForKey:P_USE_LIMIT dic:cellData];
//    NSArray *useLimitArray = [useLimit componentsSeparatedByString:@"\r\n"];
//    self.useLimitList = useLimitArray;
//    CGFloat limitY = 10;
//    for (NSString *limit in useLimitArray){
//    UILabel *useLimitLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, limitY, 290, 40)];
//    useLimitLabel.font = [UIFont fontWithName:@"TrebuchetMS" size:13.0];
//    [useLimitLabel setNumberOfLines:5];
//    useLimitLabel.text = limit;
//    [useLimitLabel sizeToFit];
//    CGRect frame = useLimitLabel.frame;
//    frame.size.width = 290;
//    useLimitLabel.frame = frame;
//    [cell.contentView addSubview:useLimitLabel];
//        limitY += frame.size.height+5;
    
//    }
    UILabel *lb_limit = [[UILabel alloc]init];
    lb_limit.lineBreakMode = UILineBreakModeWordWrap;
    lb_limit.numberOfLines = 0;
    lb_limit.text = useLimit;
    lb_limit.font = [TransforController getFontWithFont:@"Arial" andSize:14.0];
    self.useLimitList = [useLimit sizeWithFont:lb_limit.font constrainedToSize:CGSizeMake(320, MAXFLOAT) lineBreakMode:lb_limit.lineBreakMode].height + 30;
    [lb_limit setFrame:CGRectMake(0, 0, 320, self.useLimitList + 30)];
    [cell addSubview:lb_limit];
}

- (void)loadCinemaCell:(UITableViewCell*)cell
{
    if (self.goodDetail.count <= 0) {
        return;
    }
    NSDictionary *cellData = self.goodDetail;
    cell.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    UILabel *cinemaLabel = (UILabel*)[cell viewWithTag:1101];
    cinemaLabel.text = [Common valueForKey:P_NAME dic:cellData];
    UILabel *addressLabel = (UILabel*)[cell viewWithTag:1102];
    addressLabel.text = [Common valueForKey:P_ADDRESS dic:cellData];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    }
    return 1;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    view.backgroundColor = [Common colorWithRGB:0xf5f5f5];
    if (section == 2) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(15, 8, 100, 20)];
        lb.backgroundColor = [UIColor clearColor];
        lb.font = [UIFont systemFontOfSize:16];
        lb.text = @"套餐详情";
        [view addSubview:lb];
    }
    if (section == 3) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, 100, 20)];
        lb.backgroundColor = [UIColor clearColor];
        lb.font = [UIFont systemFontOfSize:16];
        lb.text = @"购买须知";
        [view addSubview:lb];
        UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(15, 40, 290, 1)];
        bottomLine.backgroundColor = [Common colorWithRGB:0xdfdfdf];
        [view addSubview:bottomLine];
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 30;
    }
    else if (section == 3)
    {
        return 40;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    switch (indexPath.section) {
            
        case 0:
            cell = [tableView dequeueReusableCellWithIdentifier:@"GoodImageCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MovieScrollCell"];
            }
            [self loadCellData:cell];
            break;
        case 1:
            cell = [tableView dequeueReusableCellWithIdentifier:@"PriceAndNameCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PriceAndNameCell"];
            }
            [self loadPriceAndNameCellData:cell index:indexPath.row];
            break;
        case 2:
            cell = [tableView dequeueReusableCellWithIdentifier:@"GoodDetailViewCell"];
            if (cell == nil) {
                cell = [[NSBundle mainBundle] loadNibNamed:@"GoodDetailViewCell"  owner:self options:nil][0];
            }
            [self loadTicketCell:cell];
            break;
        case 3:
            cell = [tableView dequeueReusableCellWithIdentifier:@"LIMITCELL"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LIMITCELL"];
            }
            [self loadUseLimitCellData:cell];
            break;
        case 4:
            cell = [tableView dequeueReusableCellWithIdentifier:@"GoodDetailViewCell"];
            if (cell == nil) {
                cell = [[NSBundle mainBundle] loadNibNamed:@"GoodDetailViewCell"  owner:self options:nil][1];
            }
            [self loadCinemaCell:cell];
            break;
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return IMAGECELL_HEIGHT;
    }
    else if (indexPath.section == 1)
    {
        return PRICE_HEIGHT;
    }
    else if (indexPath.section == 2)
    {
        return TICKET_HEIGHT;
    }
    else if (indexPath.section == 3)
    {
//        CGFloat height = _useLimitList.count * 50;
        return _useLimitList;
//        return 250;
    }
    else if (indexPath.section == 4)
    {
        return CINEMA_HEIGHT;
    }
    return STORE_LIST_CELL_HEIGHT;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Tap delegate
- (void)toBuyTicket:(UITapGestureRecognizer*)gesture
{
    OrderViewController *orderViewCtrl = [[OrderViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    orderViewCtrl.storeId = [[Common valueForKey:P_ID dic:_goodDetail] integerValue];
    orderViewCtrl.goodsInfo = self.goodsInfo;
    orderViewCtrl.storeInfo = self.storeInfo;
    NSDictionary *cellData = self.goodDetail;
    orderViewCtrl.product_name = [Common valueForKey:P_NAME dic:cellData];
    int price = [[Common valueForKey:P_PRICE dic:cellData] intValue];
    int prePrice = [[Common valueForKey:P_PREFERENTIAL_PRICE dic:cellData] intValue];
    if (prePrice >= 0 && prePrice < price) {
        price = prePrice;
    }
    orderViewCtrl.payment_mode = [NSString stringWithFormat:@"%@",[Common valueForKey:P_PAYMENT dic:cellData]];
    orderViewCtrl.product_price = [NSString stringWithFormat:@"%d",price];
    orderViewCtrl.goodsId = [Common valueForKey:P_ID dic:cellData];
    [self.navigationController pushViewController:orderViewCtrl animated:YES];
}

- (void)toMoreView:(UITapGestureRecognizer*)gesture
{
    NSDictionary *dic = self.goodDetail;
    NSString *path = [Common valueForKey:@"url" dic:dic];
    NSURL *url = [NSURL URLWithString:path];
    WebIOS *webCtrl = [[WebIOS alloc] initWithFrame:self.view.bounds url:url];
    [self.navigationController pushViewController:webCtrl animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:[NSString stringWithFormat:@"商品详情页打开，商品 id：%d，商品名：%@",[[Common valueForKey:P_ID dic:_goodDetail]intValue], [Common valueForKey:P_NAME dic:_goodDetail]]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:[NSString stringWithFormat:@"商品详情页关闭，商品 id：%d，商品名：%@",[[Common valueForKey:P_ID dic:_goodDetail]intValue], [Common valueForKey:P_NAME dic:_goodDetail]]];
}

@end
